package com.chinda.modules.sys.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.chinda.common.enums.MessageEnum;
import com.chinda.common.exception.RRException;
import com.chinda.common.utils.R;
import com.chinda.common.utils.SecurityUtil;
import com.chinda.modules.sys.dto.PasswordDTO;
import com.chinda.modules.sys.dto.SysUserDTO;
import com.chinda.modules.sys.entity.SysUserEntity;
import com.chinda.modules.sys.qo.SysUserQO;
import com.chinda.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;


/**
 * 系统用户
 *
 * @author chinda
 * @date 2021-06-16 06:03:05
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sysusers")
@Api(tags = "系统用户")
public class SysUserController {

    private final SysUserService sysUserService;

    /**
     * 分页
     *
     * @param qo
     * @return
     */
    @PostMapping("/page")
    @ApiOperation(value = "查询分页信息")
    public R page(@ApiParam(value = "qo", name = "查询实例", required = true) @RequestBody SysUserQO qo) {
        return R.ok().set(sysUserService.page(qo));
    }

    /**
     * 获取详情
     *
     * @return
     */
    @GetMapping("/{userId}")
    @ApiOperation(value = "获取详情" )
    public R info(@PathVariable("userId")  Long userId) {
        SysUserEntity sysUser = sysUserService.getById(userId);
        return R.ok().set(sysUser);
    }

    /**
     * 保存
     *
     * @return
     */
    @PostMapping
    @ApiOperation(value = "保存信息")
    public R save(@ApiParam(value = "sysUserDTO", name = "系统用户DTO实例", required = true) @RequestBody @Valid SysUserDTO sysUserDTO) {
        SysUserEntity sysUser = new SysUserEntity();
        List<Long> roleIdList = sysUserDTO.getRoleIdList();
        BeanUtil.copyProperties(sysUserDTO, sysUser, CopyOptions.create().ignoreNullValue());
        sysUserService.saveUserAndRole(sysUser, roleIdList);
        return R.ok();
    }

    /**
     * 修改全属性
     *
     * @param sysUserDTO
     * @return
     */
    @PutMapping("/{userId}")
    @ApiOperation(value = "修改全属性")
    public R modify(@PathVariable("userId") Long userId,
                    @ApiParam(value = "sysUserDTO", name = "系统用户DTO实例", required = true) @RequestBody @Valid SysUserDTO sysUserDTO) {
        SysUserEntity sysUser = new SysUserEntity();
        List<Long> roleIdList = sysUserDTO.getRoleIdList();
        BeanUtil.copyProperties(sysUserDTO, sysUser, CopyOptions.create().ignoreNullValue());
        sysUser.setUserId(userId);

        sysUserService.modifyUserAndRole(sysUser, roleIdList);
        if (!sysUserService.updateById(sysUser)) {
            throw new RRException(MessageEnum.SYS_CHECK_0012.getMsg());
        }
        return R.ok();
    }

    /**
     * 修改局部属性
     *
     * @param userId
     * @param sysUserDTO
     * @return
     */
    @PatchMapping("/{userId}")
    @ApiOperation(value = "修改局部属性")
    public R patch(@PathVariable("userId") Long userId,
                   @ApiParam(value = "sysUserDTO", name = "系统用户DTO实例", required = true) @RequestBody @Valid SysUserDTO sysUserDTO) {
        SysUserEntity dbSysUser = sysUserService.getById(userId);
        if (dbSysUser == null) {
            throw new RRException(MessageEnum.SYS_CHECK_0022.getMsg());
        }
        BeanUtil.copyProperties(sysUserDTO, dbSysUser, CopyOptions.create().ignoreNullValue());
        if (!sysUserService.updateById(dbSysUser)) {
            throw new RRException(MessageEnum.SYS_CHECK_0012.getMsg());
        }
        return R.ok();
    }

    /**
     * 删除数据
     *
     * @param userId
     * @return
     */
    @DeleteMapping("/{userId}")
    @ApiOperation(value = "删除数据")
    public R remove(@PathVariable("userId") Long userId) {
        sysUserService.removeById(userId);
        return R.ok();
    }

    /**
     * 批量删除数据
     *
     * @param userIds
     * @return
     */
    @DeleteMapping("/batch")
    @ApiOperation(value = "批量删除数据")
    public R remove(@ApiParam(value = "userIds", name = "主键集合", required = true) @RequestBody Long[] userIds) {
        // 超级管理员不允许删除
        if(CollUtil.contains(Arrays.asList(userIds), 1L)){
            return R.error("系统管理员不能删除");
        }

        // 当前用户不允许删除
        Long userId = SecurityUtil.getUserId();
        if (CollUtil.contains(Arrays.asList(userIds), userId)) {
            return R.error("当前用户不允许删除");
        }

        sysUserService.removeByIds(Arrays.asList(userIds));
        return R.ok();
    }

    /**
     * 修改登录用户密码
     */
    @PutMapping("/password")
    @ApiOperation(value = "修改密码")
    public R password(@ApiParam(value = "passwordDTO", name = "修改密码DTO", required = true) @RequestBody PasswordDTO passwordDTO){
        String newPassword = passwordDTO.getNewPassword();
        if (StrUtil.isBlank(newPassword)) {
            return R.error("新密码不允许为空");
        }

        //原密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = passwordDTO.getPassword();
        password = bCryptPasswordEncoder.encode(password);
        //新密码
        newPassword = bCryptPasswordEncoder.encode(newPassword);

        //更新密码
        if(!sysUserService.modifyPassword(password, newPassword)){
            return R.error("原密码不正确");
        }

        return R.ok();
    }
}
